<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="上下采样,交叉验证,正则化惩罚,混淆矩阵,SMOTE样本生成," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="机器学习之其他细节这一篇文章将以一个信用卡异常检测为例，介绍机器学习中一些其他非常重要的点，如样本不均、交叉验证、正则化惩罚、混淆矩阵等问题 熟悉数据信用卡数据 密码:uhst 12345678import pandas as pdimport matplotlib.pyplot as pltimport numpy as np%matplotlib inlinedata = pd.read_cs">
<meta name="keywords" content="上下采样,交叉验证,正则化惩罚,混淆矩阵,SMOTE样本生成">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习之其他细节">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/10/18/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="机器学习之其他细节这一篇文章将以一个信用卡异常检测为例，介绍机器学习中一些其他非常重要的点，如样本不均、交叉验证、正则化惩罚、混淆矩阵等问题 熟悉数据信用卡数据 密码:uhst 12345678import pandas as pdimport matplotlib.pyplot as pltimport numpy as np%matplotlib inlinedata = pd.read_cs">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/10/18/1/matrix.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/10/18/1/matrix-new.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/10/18/1/matrix-threshold.png">
<meta property="og:image" content="https://wangxiaochuang.github.io/blog/2018/10/18/1/matrix-os.png">
<meta property="og:updated_time" content="2019-01-07T22:36:29.352Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习之其他细节">
<meta name="twitter:description" content="机器学习之其他细节这一篇文章将以一个信用卡异常检测为例，介绍机器学习中一些其他非常重要的点，如样本不均、交叉验证、正则化惩罚、混淆矩阵等问题 熟悉数据信用卡数据 密码:uhst 12345678import pandas as pdimport matplotlib.pyplot as pltimport numpy as np%matplotlib inlinedata = pd.read_cs">
<meta name="twitter:image" content="https://wangxiaochuang.github.io/blog/2018/10/18/1/matrix.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/10/18/1.html"/>





  <title>机器学习之其他细节 | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/10/18/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">机器学习之其他细节</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-18T14:44:13+00:00">
                2018-10-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/其他细节/" itemprop="url" rel="index">
                    <span itemprop="name">其他细节</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/10/18/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/10/18/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/10/18/1.html" class="leancloud_visitors" data-flag-title="机器学习之其他细节">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="机器学习之其他细节"><a href="#机器学习之其他细节" class="headerlink" title="机器学习之其他细节"></a>机器学习之其他细节</h1><p>这一篇文章将以一个信用卡异常检测为例，介绍机器学习中一些其他非常重要的点，如样本不均、交叉验证、正则化惩罚、混淆矩阵等问题</p>
<h2 id="熟悉数据"><a href="#熟悉数据" class="headerlink" title="熟悉数据"></a>熟悉数据</h2><p><a href="https://pan.baidu.com/s/1UXoZkgjBF7Ye7a2-pEjz3A">信用卡数据</a> 密码:uhst</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">%matplotlib inline</span><br><span class="line"></span><br><span class="line">data = pd.read_csv(<span class="string">"creditcard.csv"</span>)</span><br><span class="line">print(data.head())</span><br><span class="line">print(data.info())</span><br></pre></td></tr></table></figure>
<p>总共有31个指标，284807条样本，其中v1到v28的指标都是标准化后的数据</p>
<ol>
<li>Time指标对信用卡检测没用，直接去掉</li>
<li>Amount值没有做过处理，需要单独标准化</li>
<li>Class指标表示当前样本是否是一个异常样本</li>
<li>我们的任务是通过逻辑回归建立一个分类的任务，检测信用卡是否异常</li>
<li>看一下样本分布情况（异常样本与正常样本分布情况）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">count_classes = pd.value_counts(data[<span class="string">'Class'</span>], sort=<span class="keyword">True</span>).sort_index()</span><br><span class="line">count_classes.plot(kind=<span class="string">'bar'</span>)</span><br><span class="line">plt.title(<span class="string">"Fraud class histogram"</span>)</span><br><span class="line">plt.xlabel(<span class="string">"class"</span>)</span><br><span class="line">plt.ylabel(<span class="string">"Frequency"</span>)</span><br></pre></td></tr></table></figure>
<p>可以看到绝大部分的样本都是正样本，极少数是负样本，在实际生活中，这也是非常常见的一种情况，毕竟坏人还是极少数的嘛</p>
<ol>
<li>将Amount数据进行标准化（让所有的指标具有相同的分布范围，消除因不同类型数据的分布差异让计算机有“偏见”）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> StandardScaler</span><br><span class="line"><span class="comment"># 注意这里的reshape(-1, 1)，-1，1表示重组后的行自动计算，列设置为1，比如：[3,2].reshape(-1, 3)，后会变成 [2, 3]</span></span><br><span class="line">data[<span class="string">'normAmount'</span>] = StandardScaler().fit_transform(data[<span class="string">'Amount'</span>].values.reshape(<span class="number">-1</span>, <span class="number">1</span>))</span><br><span class="line"><span class="comment"># normAmount为标准化后的Amount列，Time与Amount指标就可以删除了</span></span><br><span class="line">data = data.drop([<span class="string">'Time'</span>, <span class="string">'Amount'</span>], axis=<span class="number">1</span>)</span><br><span class="line">data.head()</span><br></pre></td></tr></table></figure>
<h2 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h2><h3 id="样本不均问题"><a href="#样本不均问题" class="headerlink" title="样本不均问题"></a>样本不均问题</h3><p>我们已经熟悉了数据，看到了样本极度不均，正样本（Class为1）：284315；负样本（Class为0）：492</p>
<p>对于这种情况一般有两种方式：下采样与过采样</p>
<p>下采样：让两个样本同样少</p>
<p>过采样：让两个样本同样多，将少的样本生成更多</p>
<p>这里我们先使用下采样的方式取数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">X = data.iloc[:, data.columns != <span class="string">'Class'</span>]</span><br><span class="line">y = data.iloc[:, data.columns == <span class="string">'Class'</span>]</span><br><span class="line"></span><br><span class="line">number_records_fraud = len(data[data.Class == <span class="number">1</span>])</span><br><span class="line">fraud_indices = data[data.Class == <span class="number">1</span>].index</span><br><span class="line">normal_indices = data[data.Class == <span class="number">0</span>].index</span><br><span class="line"></span><br><span class="line">random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace=<span class="keyword">False</span>)</span><br><span class="line">under_sample_indices = np.concatenate([fraud_indices, random_normal_indices])</span><br><span class="line">under_sample_data = data.iloc[under_sample_indices, :]</span><br><span class="line">X_undersample = under_sample_data.iloc[:, under_sample_data.columns != <span class="string">'Class'</span>]</span><br><span class="line">y_undersample = under_sample_data.iloc[:, under_sample_data.columns == <span class="string">'Class'</span>]</span><br><span class="line">print(<span class="string">"Percentage of normal transactions: "</span>, len(under_sample_data[under_sample_data.Class == <span class="number">0</span>]) / len(under_sample_data))</span><br><span class="line">print(<span class="string">"Percentage of fraud transactions: "</span>, len(under_sample_data[under_sample_data.Class == <span class="number">1</span>]) / len(under_sample_data))</span><br><span class="line">print(<span class="string">"Total number of transactions in resampled data: "</span>, len(under_sample_data))</span><br><span class="line"><span class="comment"># Percentage of normal transactions:  0.5</span></span><br><span class="line"><span class="comment"># Percentage of fraud transactions:  0.5</span></span><br><span class="line"><span class="comment"># Total number of transactions in resampled data:  984</span></span><br></pre></td></tr></table></figure>
<p>我们从正样本中随机选择了和负样本同样数量的样本，并组合在一起为一个下采样动作</p>
<h3 id="交叉验证"><a href="#交叉验证" class="headerlink" title="交叉验证"></a>交叉验证</h3><p>当我们在做一个机器学习任务的时候都是将原始数据切分为训练集与测试集，比如训练集（80%），测试集（20%），其中的20%测试的测试集非常宝贵，用于最后的模型评估，我们这里要说的交叉验证是不涉及测试集的</p>
<p>另一方面，当我们在进行模型训练的时候，我们需要一步一步的选择更好的参数去拟合我们的数据，这需要一个评判标准，这个时候我们会再次将我们的训练数据切分为几个部分（为了更好说明，假如就三个部分），我们会分别做三次训练，最后取一个参数的均值。这三次分别为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1. a + b &lt;==&gt; c</span><br><span class="line">2. a + c &lt;==&gt; b</span><br><span class="line">3. b + c &lt;==&gt; a</span><br></pre></td></tr></table></figure>
<p>这里的a b c 分别各做了一次验证集，这么一个过程称为交叉验证，下面我们使用sklean工具包帮我们完成切分</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.cross_validation <span class="keyword">import</span> train_test_split</span><br><span class="line"><span class="comment"># 既然都说了使用下采样了，其余数据就应该扔掉了，怎么还要拿来用呢？</span></span><br><span class="line"><span class="comment"># 主要原因是下采样的数据比较少，分布规则可能不惧代表性，因此会拿原始数据集来进行测试</span></span><br><span class="line">X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=<span class="number">0.3</span>, random_state=<span class="number">0</span>)</span><br><span class="line">print(<span class="string">"Number transactions train dataset: "</span>, len(X_train))</span><br><span class="line">print(<span class="string">"Number transactions test dataset: "</span>, len(X_test))</span><br><span class="line">print(<span class="string">"Total number of transactions: "</span>, len(X_train) + len(X_test))</span><br><span class="line">X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample, y_undersample, test_size=<span class="number">0.3</span>, random_state=<span class="number">0</span>)</span><br><span class="line">print(<span class="string">""</span>)</span><br><span class="line">print(<span class="string">"Number transactions train dataset: "</span>, len(X_train_undersample))</span><br><span class="line">print(<span class="string">"Number transacyions test dataset: "</span>, len(X_test_undersample))</span><br><span class="line">print(<span class="string">"Total number of transactions: "</span>, len(X_train_undersample) + len(X_test_undersample))</span><br></pre></td></tr></table></figure>
<h3 id="模型评估方法"><a href="#模型评估方法" class="headerlink" title="模型评估方法"></a>模型评估方法</h3><p>这里我们讨论一下，我们的模型评估标准，怎么样的结果算是比较满意的结果呢？</p>
<p>这里我们举一个例子：</p>
<blockquote>
<p>将设有1000个病人（990个正样本，10个负样本）的样本信息，我们要建立模型预测病人是否得了癌症，我们使用精度来判断模型好坏。<br>假设我们的模型把全部样本都预测为正样本（没有得癌症），那么这个时候我们的模型的精度是多少呢？990/1000=99%<br>但是这个时候，我们的模型有用吗？一点用都没有嘛，因此这种评估方法是非常有问题的</p>
</blockquote>
<p>特别是针对正负样本严重不均的情况下，这种精度的评估方法非常烂，这个时候一般使用一个叫做<code>recall(召回率)</code>的评估方法，怎么理解呢？</p>
<blockquote>
<p>还是以上面检测癌症的例子，我们现在不检测正样本的精度，而是检测负样本的精度，及求10个癌症病人中，我们检测出来了几个癌症病人。</p>
</blockquote>
<p>这里给出Recall的公式：<code>Recall = TP / (TP + FN)</code>，这里有的解释一下了</p>
<h4 id="关于Recall的计算的几个概念"><a href="#关于Recall的计算的几个概念" class="headerlink" title="关于Recall的计算的几个概念"></a>关于Recall的计算的几个概念</h4><blockquote>
<p>假如某个班级有男生80人，女生20人，共计100人，目标是找出所有女生<br>现在某个挑选出50个人，其中20个人士女生，另外还错误的把30个男生也当做女生选了出来</p>
</blockquote>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center"></th>
<th>相关（Relevant），正类</th>
<th>无关（NonRelevant），负类</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">被检索到<br>（Retrieved）</td>
<td>true positives（TP 正类判定为正类，例子中就是正确的判定为女生）</td>
<td>false positives（FP 负类判定为正类，例子中就是将男生判断为女生）</td>
</tr>
<tr>
<td style="text-align:center">未被检索到<br>（Not Retrieved）</td>
<td>false negatives（FN 正类判定为负累，“去真”，例子中就是，将女生判定为男生）</td>
<td>true negatives（TN 负类判定为负类，例子中就是吧男生判定为男生）</td>
</tr>
</tbody>
</table>
</div>
<p>通过上面这种病，我们可以非常容易得到Recall值：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">TP = 20</span><br><span class="line">FP = 30</span><br><span class="line">FN = 0</span><br><span class="line">TN = 50</span><br><span class="line">Recall = TP / (TP + FN) = 20 / (20 + 50)</span><br></pre></td></tr></table></figure>
<p>对于实现来说，sklearn已经帮我们做好了</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="正则化惩罚"><a href="#正则化惩罚" class="headerlink" title="正则化惩罚"></a>正则化惩罚</h3><p>假设现在对于一个任务，我们有两个模型，A和B。</p>
<p>A模型的各个参数值变化浮动比较大，B模型的各个参数值变化浮动比较小，但是模型在训练集上的效果是一样的，这个时候我们需要有一种方法将B模型选择出来（为什么要选择参数浮动小的模型：模型更稳定，除了你和测试数据效果不错外，还要能完美拟合真实数据）</p>
<p>对于这种情况，在机器学习里面，常用两种名为正则化惩罚的方式（L1惩罚项与L2惩罚项）。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"># 权重参数的绝对值</span><br><span class="line">L1: loss + |w|</span><br><span class="line"></span><br><span class="line"># 权重参数的平方</span><br><span class="line">L2: loss + 1/2 x w^2</span><br><span class="line"></span><br><span class="line"># 还有一个惩罚力度 alpha，表示惩罚力度</span><br><span class="line"></span><br><span class="line"># 如果使用sklean，在使用逻辑回归工具的时候，会让输入惩罚力度与惩罚方法</span><br><span class="line"></span><br><span class="line">from sklearn.linear_model import LogisticRegression</span><br><span class="line">lr = LogisticRegression(C = 0.01, penalty = &apos;l1&apos;)</span><br></pre></td></tr></table></figure>
<p>这里我们结合信用卡欺诈的例子，以recall值为判断标准，比对一下不同的惩罚力度对结果的影响</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">printing_Kfold_scores</span><span class="params">(x_train_data, y_train_data)</span>:</span></span><br><span class="line">    <span class="comment"># 交叉验证的数据切分，这里按y_train_data的长度将训练集切分为5分，进行交叉验证</span></span><br><span class="line">    fold = KFold(len(y_train_data), <span class="number">5</span>, shuffle=<span class="keyword">False</span>)</span><br><span class="line">    c_param_range = [<span class="number">0.01</span>, <span class="number">0.1</span>, <span class="number">1</span>, <span class="number">10</span>, <span class="number">100</span>]</span><br><span class="line">    results_table = pd.DataFrame(index=range(len(c_param_range), <span class="number">2</span>), columns=[<span class="string">'C_parameter'</span>, <span class="string">'Mean recall score'</span>])</span><br><span class="line">    results_table[<span class="string">'C_parameter'</span>] = c_param_range</span><br><span class="line">    </span><br><span class="line">    j = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> c_param <span class="keyword">in</span> c_param_range:</span><br><span class="line">        print(<span class="string">'-----------------------------'</span>)</span><br><span class="line">        print(<span class="string">'C parameter: '</span>, c_param)</span><br><span class="line">        print(<span class="string">'-----------------------------'</span>)</span><br><span class="line">        print(<span class="string">''</span>)</span><br><span class="line">        recall_accs = []</span><br><span class="line">        <span class="keyword">for</span> iteration, indices <span class="keyword">in</span> enumerate(fold, start=<span class="number">1</span>):</span><br><span class="line">            <span class="comment"># 遍历fold，indices[0]为交叉验证的训练集，indices[1]为交叉验证的测试集</span></span><br><span class="line">            lr = LogisticRegression(C = c_param, penalty = <span class="string">'l1'</span>)</span><br><span class="line">            lr.fit(x_train_data.iloc[indices[<span class="number">0</span>], :], y_train_data.iloc[indices[<span class="number">0</span>], :].values.ravel())</span><br><span class="line">            <span class="comment"># 拿交叉验证的测试集去预测结果</span></span><br><span class="line">            y_pred_undersample = lr.predict(x_train_data.iloc[indices[<span class="number">1</span>], :].values)</span><br><span class="line">            <span class="comment"># 当次交叉验证的recall值</span></span><br><span class="line">            recall_acc = recall_score(y_train_data.iloc[indices[<span class="number">1</span>],:].values, y_pred_undersample)</span><br><span class="line">            recall_accs.append(recall_acc)</span><br><span class="line">            print(<span class="string">'Iteration '</span>, iteration, <span class="string">': recall score = '</span>, recall_acc)</span><br><span class="line">        </span><br><span class="line">        results_table.loc[j, <span class="string">'Mean recall score'</span>] = np.mean(recall_accs)</span><br><span class="line">        j += <span class="number">1</span></span><br><span class="line">        print(<span class="string">''</span>)</span><br><span class="line">        print(<span class="string">'Mean recall score '</span>, np.mean(recall_accs))</span><br><span class="line">        print(<span class="string">''</span>)</span><br><span class="line">        </span><br><span class="line">    <span class="comment"># 这里需要将这个字段的值类型转为float64，在程序运行过程莫名其妙就转成了object</span></span><br><span class="line">    results_table[<span class="string">'Mean recall score'</span>] = results_table[<span class="string">'Mean recall score'</span>].astype(<span class="string">'float64'</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 求效果最好的惩罚力度值</span></span><br><span class="line">    best_c = results_table.loc[results_table[<span class="string">'Mean recall score'</span>].idxmax()][<span class="string">'C_parameter'</span>]</span><br><span class="line">    print(<span class="string">'******************************************************'</span>)</span><br><span class="line">    print(<span class="string">'Best model to choose from cross validation is with C parameter = '</span>, best_c)</span><br><span class="line">    print(<span class="string">'******************************************************'</span>)</span><br><span class="line">    <span class="keyword">return</span> best_c</span><br><span class="line"></span><br><span class="line">printing_Kfold_scores(X_train_undersample, y_train_undersample)</span><br><span class="line"><span class="comment"># 达到结果，比较好的惩罚力度是0.01</span></span><br><span class="line"><span class="comment"># 通过结果也能看到在交叉验证的过程中某些结果的差异还是蛮大的，可能差10个百分点，所以使用交叉验证求平均的方式还是非常有用的</span></span><br></pre></td></tr></table></figure>
<p>为了更好的看到下采样的优势，我们对比一下，直接用原始数据计算recall值：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">printing_Kfold_scores(X_train_undersample, y_train_undersample)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 两种方式的结果可以看到，直接使用原始数据进行计算，recall值都在0.6左右，而使用下采样能够达到0.9</span></span><br></pre></td></tr></table></figure>
<h3 id="混淆矩阵"><a href="#混淆矩阵" class="headerlink" title="混淆矩阵"></a>混淆矩阵</h3><p>混淆矩阵就是展示与Recall相关的几个指标的图形，这里我们拿上一段计算出来的best_c，来看一下我们的混淆矩阵长什么样</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">plot_confusion_matrix</span><span class="params">(cm, classes, title=<span class="string">'Confusion matrix'</span>, cmap=plt.cm.Blues)</span>:</span></span><br><span class="line">    plt.imshow(cm, interpolation=<span class="string">'nearest'</span>, cmap=cmap)</span><br><span class="line">    plt.title(title)</span><br><span class="line">    plt.colorbar()</span><br><span class="line">    tick_marks = np.arange(len(classes))</span><br><span class="line">    plt.xticks(tick_marks, classes, rotation=<span class="number">0</span>)</span><br><span class="line">    plt.yticks(tick_marks, classes)</span><br><span class="line">    thresh = cm.max() / <span class="number">2</span></span><br><span class="line">    <span class="keyword">for</span> i, j <span class="keyword">in</span> itertools.product(range(cm.shape[<span class="number">0</span>]), range(cm.shape[<span class="number">1</span>])):</span><br><span class="line">        plt.text(j, i, cm[i, j], horizontalalignment=<span class="string">"center"</span>, color=<span class="string">"white"</span> <span class="keyword">if</span> cm[i, j] &gt; thresh <span class="keyword">else</span> <span class="string">"black"</span>)</span><br><span class="line">    plt.tight_layout()</span><br><span class="line">    plt.ylabel(<span class="string">'True label'</span>)</span><br><span class="line">    plt.xlabel(<span class="string">'Predicted label'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> itertools</span><br><span class="line">lr = LogisticRegression(C=best_c, penalty=<span class="string">'l1'</span>)</span><br><span class="line">lr.fit(X_train_undersample, y_train_undersample.values.ravel())</span><br><span class="line">y_pred_undersample = lr.predict(X_test_undersample.values)</span><br><span class="line">cnf_matrix = confusion_matrix(y_test_undersample, y_pred_undersample)</span><br><span class="line">np.set_printoptions(precision=<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">print(<span class="string">"Recall metrix in the testing dataset: "</span>, cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]/(cnf_matrix[<span class="number">1</span>,<span class="number">0</span>]+cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]))</span><br><span class="line">class_names = [<span class="number">0</span>,<span class="number">1</span>]</span><br><span class="line">plt.figure()</span><br><span class="line">plot_confusion_matrix(cnf_matrix, classes=class_names, title=<span class="string">'Confusion matrix'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<p>得到如下结果：</p>
<img src="/blog/2018/10/18/1/matrix.png" title="在下采样测试样本下混淆矩阵">
<p>其中y轴表示样本真实的情况，x轴表示模型预测的情况</p>
<p>通过混淆矩阵我们非常容易计算出recall值，同时精度值也非常容易求出来</p>
<p>这个举证我们是在下采样数据集中测试的，但是为了更好的评估模型的好坏，我们需要再所有数据的测试集上去测试，我们看下结果吧（只需要改一下预测的数据即可）：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> itertools</span><br><span class="line">lr = LogisticRegression(C=best_c, penalty=<span class="string">'l1'</span>)</span><br><span class="line">lr.fit(X_train_undersample, y_train_undersample.values.ravel())</span><br><span class="line">y_pred = lr.predict(X_test.values)</span><br><span class="line">cnf_matrix = confusion_matrix(y_test, y_pred)</span><br><span class="line">np.set_printoptions(precision=<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">print(<span class="string">"Recall metrix in the testing dataset: "</span>, cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]/(cnf_matrix[<span class="number">1</span>,<span class="number">0</span>]+cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]))</span><br><span class="line">class_names = [<span class="number">0</span>,<span class="number">1</span>]</span><br><span class="line">plt.figure()</span><br><span class="line">plot_confusion_matrix(cnf_matrix, classes=class_names, title=<span class="string">'Confusion matrix'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<img src="/blog/2018/10/18/1/matrix-new.png" title="在原始测试样本下的混淆矩阵">
<p>你能看出有什么区别么？</p>
<p>对于计算Recall（Recall = TP / (TP + FN)）值来说，变化不大，但是我们的误杀率特别高，为了检测这135个异常样本，结果多误杀了8662个样本</p>
<p>通过对比我们能够看到，对于下采样获取数据集来说，虽然我们能够满足Recall值的要求，但是误杀就太多太多了</p>
<h3 id="不同阈值对recall值的影响"><a href="#不同阈值对recall值的影响" class="headerlink" title="不同阈值对recall值的影响"></a>不同阈值对recall值的影响</h3><p>还记得之前的介绍的，逻辑回归时间预测的结果值转换为概率么？默认情况下我们将概率大于0.5的认为是异常信用卡，那有没有考虑这个0.5可以变化一下呢？这里我们还是对比一下不同的阈值对recall值的影响</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">lr = LogisticRegression(C=<span class="number">0.01</span>, penalty=<span class="string">'l1'</span>)</span><br><span class="line">lr.fit(X_train_undersample, y_train_undersample.values.ravel())</span><br><span class="line"><span class="comment"># 预测出来的是概率值</span></span><br><span class="line">y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)</span><br><span class="line">thresholds = [<span class="number">0.1</span>,<span class="number">0.2</span>,<span class="number">0.3</span>,<span class="number">0.4</span>,<span class="number">0.5</span>,<span class="number">0.6</span>,<span class="number">0.7</span>,<span class="number">0.8</span>,<span class="number">0.9</span>]</span><br><span class="line">plt.figure(figsize=(<span class="number">10</span>,<span class="number">10</span>))</span><br><span class="line">j = <span class="number">1</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> thresholds:</span><br><span class="line">    y_test_predictions_hight_recall = y_pred_undersample_proba[:,<span class="number">1</span>] &gt; i</span><br><span class="line">    plt.subplot(<span class="number">3</span>,<span class="number">3</span>,j)</span><br><span class="line">    j += <span class="number">1</span></span><br><span class="line">    cnf_matrix = confusion_matrix(y_test_undersample, y_test_predictions_hight_recall)</span><br><span class="line">    np.set_printoptions(precision=<span class="number">2</span>)</span><br><span class="line">    print(<span class="string">"Recall metric in the testing dataset: "</span>, cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]/(cnf_matrix[<span class="number">1</span>,<span class="number">0</span>] + cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]))</span><br><span class="line">    </span><br><span class="line">    class_names = [<span class="number">0</span>,<span class="number">1</span>]</span><br><span class="line">    plot_confusion_matrix(cnf_matrix, classes=class_names, title=<span class="string">'Threshold &gt;= %s'</span> % i)</span><br></pre></td></tr></table></figure>
<p>可以得到结果：</p>
<img src="/blog/2018/10/18/1/matrix-threshold.png" title="不同阈值下的的混淆矩阵">
<p>可以得出结论：</p>
<ol>
<li>随着阈值的上升，recall值逐渐减少，但是误杀也在减少</li>
<li>阈值过小或过大，精度会比较小</li>
</ol>
<p>在实际工作中，我们可能是有一些指标的，比如误杀率不能超过多少，精度要大于多少等，我们就可以根据这些指标来选择合适的参数</p>
<h3 id="SMOTE样本生成策略"><a href="#SMOTE样本生成策略" class="headerlink" title="SMOTE样本生成策略"></a>SMOTE样本生成策略</h3><p>前面我们都是基于下采样来处理样本不平衡问题，这里我们讨论过采样方法，这就不得不提到SMOTE样本生成策略了。</p>
<p>过采样的意思就是将少数类样本进行采样，扩展其样本数量。</p>
<p>SMOTE算法解释：</p>
<blockquote>
<ol>
<li>以少类样本为基础，遍历每一个少类样本，假设有n个少类样本</li>
<li>分别找到离这n个少类样本，欧式距离最近的m个样本</li>
<li>再依次遍历这m个样本，在两个点中间随机选择k个点作为新增的点</li>
</ol>
</blockquote>
<p>可以参考这篇文章：<a href="https://www.jianshu.com/p/ecbc924860af">SMOTE</a></p>
<p>在python中有一个叫做 <code>imblearn</code>的库，通过 <code>pip install imblearn</code> 安装即可</p>
<p>这里我们从头开始做一遍信用卡欺诈检测任务，使用过采样方式：</p>
<ol>
<li><p>导入一些必要的库</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> imblearn.over_sampling <span class="keyword">import</span> SMOTE</span><br><span class="line"><span class="keyword">from</span> sklearn.ensemble <span class="keyword">import</span> RandomForestClassifier</span><br><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LogisticRegression</span><br><span class="line"><span class="keyword">from</span> sklearn.metrics <span class="keyword">import</span> confusion_matrix</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> train_test_split</span><br></pre></td></tr></table></figure>
</li>
<li><p>拆分数据，并进行过采样补齐</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">credit_cards = pd.read_csv(<span class="string">'./creditcard.csv'</span>)</span><br><span class="line">columns = credit_cards.columns</span><br><span class="line">features_columns = columns.delete(len(columns)<span class="number">-1</span>)</span><br><span class="line">features = credit_cards[features_columns]</span><br><span class="line">labels = credit_cards[<span class="string">'Class'</span>]</span><br><span class="line"></span><br><span class="line">features_train, features_test, labels_train, labels_test = train_test_split(features,</span><br><span class="line">                                                                           labels,</span><br><span class="line">                                                                           test_size=<span class="number">0.2</span>,</span><br><span class="line">                                                                           random_state=<span class="number">0</span>)</span><br><span class="line">oversampler = SMOTE(random_state=<span class="number">0</span>)</span><br><span class="line"><span class="comment"># 特别注意：这里采样的的训练集数据，测试集数据时不能动的</span></span><br><span class="line">os_features, os_labels = oversampler.fit_sample(features_train, labels_train)</span><br><span class="line">print(<span class="string">"the number of class = 1, after oversample: %d"</span> % len(os_labels[os_labels==<span class="number">1</span>]))</span><br></pre></td></tr></table></figure>
<ol>
<li>我们再看针对过采样的方式，不同的正则化惩罚力度对recall的影响</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">os_features = pd.DataFrame(os_features)</span><br><span class="line">os_labels = pd.DataFrame(os_labels)</span><br><span class="line">best_c = printing_Kfold_scores(os_features, os_labels)</span><br></pre></td></tr></table></figure>
<p>通过结果可以看到recall值比小采样的稍小一些，但别急，看其他指标</p>
<ol>
<li>我们再看看混淆矩阵的结果如何</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> itertools</span><br><span class="line">lr = LogisticRegression(C=best_c, penalty=<span class="string">'l1'</span>)</span><br><span class="line">lr.fit(os_features, os_labels.values.ravel())</span><br><span class="line">y_pred = lr.predict(features_test.values)</span><br><span class="line"></span><br><span class="line">cnf_matrix = confusion_matrix(labels_test, y_pred)</span><br><span class="line">np.set_printoptions(precision=<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">print(<span class="string">"Recall metric in the testing dataset: "</span>, cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]/(cnf_matrix[<span class="number">1</span>,<span class="number">0</span>]+cnf_matrix[<span class="number">1</span>,<span class="number">1</span>]))</span><br><span class="line">class_names = [<span class="number">0</span>, <span class="number">1</span>]</span><br><span class="line">plt.figure()</span><br><span class="line">plot_confusion_matrix(cnf_matrix, classes=class_names, title=<span class="string">'Confusion matrix'</span>)</span><br></pre></td></tr></table></figure>
<p>看看结果：</p>
<img src="/blog/2018/10/18/1/matrix-os.png" title="过采样下的的混淆矩阵">
<p>我们需要上面的下采样的结果进行对比，可以看出recall低了一些，但是误杀率减少了很多，过采样误杀8000多个，现在只有500多个</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文通过实验测试了针对模型的不同参数，可能对结果产生非常大的影响。我们需要根据实际情况选择合适的参数</p>
<p>这里是以逻辑回归为例，但是很多点都是机器学习中通用的思路</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/上下采样/" rel="tag"># 上下采样</a>
          
            <a href="/blog/tags/交叉验证/" rel="tag"># 交叉验证</a>
          
            <a href="/blog/tags/正则化惩罚/" rel="tag"># 正则化惩罚</a>
          
            <a href="/blog/tags/混淆矩阵/" rel="tag"># 混淆矩阵</a>
          
            <a href="/blog/tags/SMOTE样本生成/" rel="tag"># SMOTE样本生成</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/10/17/1.html" rel="next" title="机器学习之逻辑回归（代码实现）">
                <i class="fa fa-chevron-left"></i> 机器学习之逻辑回归（代码实现）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/10/20/1.html" rel="prev" title="机器学习之决策树算法">
                机器学习之决策树算法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#机器学习之其他细节"><span class="nav-number">1.</span> <span class="nav-text">机器学习之其他细节</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#熟悉数据"><span class="nav-number">1.1.</span> <span class="nav-text">熟悉数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#问题"><span class="nav-number">1.2.</span> <span class="nav-text">问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#样本不均问题"><span class="nav-number">1.2.1.</span> <span class="nav-text">样本不均问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#交叉验证"><span class="nav-number">1.2.2.</span> <span class="nav-text">交叉验证</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模型评估方法"><span class="nav-number">1.2.3.</span> <span class="nav-text">模型评估方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#关于Recall的计算的几个概念"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">关于Recall的计算的几个概念</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#正则化惩罚"><span class="nav-number">1.2.4.</span> <span class="nav-text">正则化惩罚</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#混淆矩阵"><span class="nav-number">1.2.5.</span> <span class="nav-text">混淆矩阵</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不同阈值对recall值的影响"><span class="nav-number">1.2.6.</span> <span class="nav-text">不同阈值对recall值的影响</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SMOTE样本生成策略"><span class="nav-number">1.2.7.</span> <span class="nav-text">SMOTE样本生成策略</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">1.3.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
